import TextEditor from '@/pages/cues/components/TextEditor';
import { saveInstructRecord, saveRecordInitAssign } from '@/services/api/api-instruct-record';
import {
  CheckCircleTwoTone,
  FileSearchOutlined,
  SendOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProCard,
  ProForm,
  ProFormDateTimePicker,
  ProFormGroup,
  ProFormInstance,
  ProFormRadio,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Avatar, Button, Divider, message } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { useAccess, useModel } from 'umi';
import AssignAccount from '../assign/AssignAccount';
import AssignContact from '../assign/AssignContact';
import UploadDragger from '../components/UploadDragger';
interface AddRecordProps {
  onSave: () => void;
}

const AddRecord: React.FC<AddRecordProps> = ({ onSave }) => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const access = useAccess();
  const formRef = useRef<ProFormInstance>();

  const [vaisibleReadRequest, setVisibleReadReauestState] = useState(false);
  const [vaisibleReceiptRequest, setVisibleReceiptReauestState] = useState(false);
  const [vaisibleRequest, setVisibleReauestState] = useState(false);

  const [accountsLenght, setAccountsLenghtState] = useState();

  const initTinyMce = () => { };

  //自定义联络人（多选）
  const [visibleAssignAccount, setVisibleAssignAccountState] = useState<boolean>(true);
  const [dataAssignsAccounts, setDataAssignsAccountsState] = useState<
    UserData.OrganizationOption[]
  >([]);

  //联络人（多选）
  const [visibleAssignContact, setVisibleAssignContactState] = useState<boolean>(false);
  const [dataAssignsContactss, setDataAssignsContactssState] = useState<
    UserData.OrganizationOption[]
  >([]);

  const [content, setContentState] = useState<string>('');

  const [isUpload, setIsUploadState] = useState<boolean>(false);

  const [openAddSubmit, setOpenAddSubmit] = useState<boolean>(false);

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  useEffect(() => { }, [vaisibleRequest]);
  /**
   * 加载话题配置
   * @param key
   */
  const initConfigData = async () => {
    try {
      const response = await saveRecordInitAssign();
      if (response.code === 0) {
        setDataAssignsAccountsState(response.data.assignsAccounts);
        setDataAssignsContactssState(response.data.assignsContacts);
      }
    } catch (error) { }
  };

  const range = (start: number, end: number) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  return (
    <DrawerForm
      title="发布指令"
      trigger={
        <Button key="button" type="primary" icon={<SendOutlined />}>
          发布指令
        </Button>
      }
      layout="horizontal"
      formRef={formRef}
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        // forceRender: true,
        destroyOnClose: true,
        maskClosable: false,
        width: 1150,
        closable: true,
      }}
      initialValues={{
        assignType: '4',
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        searchConfig: {
          submitText: (
            <>
              <FileSearchOutlined /> 预览
            </>
          ),
        },
        render: (props, defaultDoms) => {
          return [
            defaultDoms,
            <Button
              key="button_add_submit"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                /**
                 * ======================
                 * 直接发布
                 * ======================
                 */
                const values = formRef.current?.getFieldsValue();

                console.log(values);
                if (values.grade === undefined || values.grade === 0) {
                  message.warning('请选择分类');
                  return;
                }

                if (values.type === undefined || values.type === 0) {
                  message.warning('请选择渠道');
                  return;
                }
                if (
                  values.name === undefined ||
                  values.name.length === 0 ||
                  values.name.trim() === ''
                ) {
                  message.warning('请输入标题');
                  return;
                }

                if (values.deadlineTime === undefined) {
                  message.warning('请选择截止时间');
                  return;
                }

                if (values.isDisappear === undefined) {
                  message.warning('请选择是否焚毁');
                  return;
                }

                if (
                  visibleAssignAccount &&
                  (values.assignAccounts === undefined || values.assignAccounts.length === 0)
                ) {
                  message.warning('请选择至少一个联络人');
                  return;
                }
                if (
                  values.completeType === undefined ||
                  values.completeType.length === 0 ||
                  values.completeType.trim() === ''
                ) {
                  message.warning('请选择指令要求');
                  return;
                }

                if (isUpload) {
                  message.warning('附件正在上传，请稍后再试！');
                  return;
                }

                if (
                  visibleAssignContact &&
                  (values.assignContacts === undefined || values.assignContacts.length === 0)
                ) {
                  message.warning('请选择至少一个接收人');
                  return;
                }
                if (
                  values.content === undefined ||
                  values.content.length === 0 ||
                  values.content.trim() === ''
                ) {
                  message.warning('请输入内容');
                  return;
                }
                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_add_submit'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: '30%',
                destroyOnClose: true,
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                props.submit();
                return true;
              }}
            >
              提交后，将自动推送指令！
            </ModalForm>,
          ];
        },
      }}
      onFinish={async (values) => {
        console.log('================', values);

        if (values.grade === undefined || values.grade === 0) {
          message.warning('请选择分类');
          return;
        }

        if (values.type === undefined || values.type === 0) {
          message.warning('请选择渠道');
          return;
        }

        if (values.deadlineTime === undefined) {
          message.warning('请选择截止时间');
          return;
        }

        if (values.isDisappear === undefined) {
          message.warning('请选择是否焚毁');
          return;
        }

        if (isUpload) {
          message.warning('附件正在上传，请稍后再试！');
          return;
        }

        if (values.name === undefined || values.name.length === 0 || values.name.trim() === '') {
          message.warning('请输入标题');
          return;
        }

        if (
          visibleAssignAccount &&
          (values.assignAccounts === undefined || values.assignAccounts.length === 0)
        ) {
          message.warning('请选择至少一个联络人');
          return;
        }

        if (
          visibleAssignContact &&
          (values.assignContacts === undefined || values.assignContacts.length === 0)
        ) {
          message.warning('请选择至少一个接收人');
          return;
        }

        if (
          values.content === undefined ||
          values.content.length === 0 ||
          values.content.trim() === ''
        ) {
          message.warning('请输入内容');
          return;
        }
        console.log(values.completeType);

        if (
          values.completeType === undefined ||
          values.completeType.length === 0 ||
          values.completeType.trim() === ''
        ) {
          message.warning('请选择指令要求');
          return;
        }

        if (values.attachments !== undefined && values.attachments.length > 0) {
          const attachments = values.attachments
            .filter((item: { status: string }) => {
              return item.status === 'done';
            })
            .map((item: { response: { data: { id: any } } }) => {
              return item.response.data.id;
            });

          values.attachments = attachments;
        }

        const response = await saveInstructRecord(values);
        if (response.code === 0) {
          message.success('提交成功');
          // const pushBulletinResponse = await pushRecord({ id: response.data.id });
          // if (pushBulletinResponse.code === 0) {
          //   message.success('推送成功');
          // }
          // Modal.confirm({
          //   title: '发布成功，是否要全局推送？',
          //   icon: <ExclamationCircleOutlined />,
          //   content: '全局推送：对所选用户组进行短信通知。',
          //   async onOk() {
          //     const pushBulletinResponse = await pushRecord({ id: response.data.id });
          //     if (pushBulletinResponse.code === 0) {
          //       message.success('推送成功');
          //     }
          //   },
          //   onCancel() { },
          // });
          onSave();
          return true;
        } else {
          return false;
        }
      }}
      onValuesChange={(changedValues: any, allValues: any) => {
        setVisibleAssignAccountState(allValues.assignType === '4');
        setVisibleAssignContactState(allValues.assignType === '5');
        setVisibleReadReauestState(allValues.completeType === '2');
        setVisibleReceiptReauestState(allValues.completeType === '3');
      }}
      onOpenChange={(visible) => {
        if (visible) {
          initConfigData();
          setVisibleAssignAccountState(true);
        } else {
          setVisibleAssignAccountState(false);
          setVisibleAssignContactState(false);
          setVisibleReauestState(false);
        }
      }}
    >
      <ProFormRadio.Group
        name="grade"
        radioType="button"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            分类
          </>
        }
        onChange={(value) => {
          const grade = value.target.value;
          formRef.current?.setFieldsValue({
            grade: grade,
          });
        }}
        options={[
          {
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar style={{ backgroundColor: '#f50' }} icon={<UserOutlined />} size={20} />
                <span style={{ marginLeft: 5 }}>重大</span>
              </div>
            ),
            value: 1,
          },
          {
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar style={{ backgroundColor: '#ffd591' }} icon={<UserOutlined />} size={20} />
                <span style={{ marginLeft: 5 }}>重要</span>
              </div>
            ),
            value: 2,
          },
          {
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar style={{ backgroundColor: '#2db7f5' }} icon={<UserOutlined />} size={20} />
                <span style={{ marginLeft: 5 }}>一般</span>
              </div>
            ),
            value: 3,
          },
        ]}
        fieldProps={{
          style: {
            marginLeft: '28px',
          },
          buttonStyle: 'solid',
        }}
      />

      <ProFormRadio.Group
        name="type"
        radioType="button"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            渠道
          </>
        }
        onChange={(value) => {
          const type = value.target.value;
          formRef.current?.setFieldsValue({
            type: type,
          });
        }}
        options={[
          {
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar style={{ backgroundColor: '#f50' }} icon={<UserOutlined />} size={20} />
                <span style={{ marginLeft: 5 }}>中宣</span>
              </div>
            ),
            value: 1,
          },
          {
            label: (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Avatar style={{ backgroundColor: '#ffd591' }} icon={<UserOutlined />} size={20} />
                <span style={{ marginLeft: 5 }}>市宣</span>
              </div>
            ),
            value: 2,
          },
        ]}
        fieldProps={{
          style: {
            marginLeft: '28px',
          },
          buttonStyle: 'solid',
        }}
      />

      <ProFormTextArea
        width="xl"
        name="name"
        required
        label="标题"
        // tooltip="最长为 24 位"
        placeholder="请输入名称"
        fieldProps={{
          allowClear: true,
          rows: 2,
          maxLength: 200,
          style: {
            marginLeft: '28px',
          },
        }}
        rules={[{ required: true, message: '这是必填项' }]}
      />
      <ProFormDateTimePicker
        width="xl"
        name="deadlineTime"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            截止时间
          </>
        }
        extra="到达设定的截止时候后，系统会关闭该指令"
        fieldProps={{
          minDate: dayjs(),
          presets: [
            { label: '后3天', value: dayjs().add(3, 'd') },
            { label: '后5天', value: dayjs().add(5, 'd') },
            { label: '后7天', value: dayjs().add(7, 'd') },
            { label: '后10天', value: dayjs().add(10, 'd') },
            { label: '后15天', value: dayjs().add(15, 'd') },
            { label: '后20天', value: dayjs().add(20, 'd') },
            { label: '后30天', value: dayjs().add(30, 'd') },
            { label: '后50天', value: dayjs().add(50, 'd') },
            { label: '后90天', value: dayjs().add(90, 'd') },
          ],
          format: 'YYYY-MM-DD HH:mm:ss',
        }}
      />
      <ProFormGroup>
        <ProFormRadio.Group
          name="isDisappear"
          label={'到期焚毁'}
          options={[
            {
              label: '是',
              value: '1',
            },
            {
              label: '否',
              value: '0',
            },
          ]}
          rules={[{ required: true, message: '请选择到期是否焚毁该指令' }]}
        />
      </ProFormGroup>
      <ProFormGroup>
        <ProFormRadio.Group
          name="completeType"
          label="指令要求"
          options={[
            {
              label: '无需回执',
              value: '1',
            },
            {
              label: '需要回执',
              value: '3',
            },
          ]}
          rules={[{ required: true, message: '请选择报送范围' }]}
        // fieldProps={{
        //   onChange:(e)=>{
        //     console.log(e.target.value);
        //     if(e.target.value==='1'){
        //       setVisibleReadReauestState(false)
        //     }
        //   }
        // }}
        // tooltip="默认为全部，即所有机构，包括中央媒体"
        />
      </ProFormGroup>
      <ProFormGroup>
        <ProFormRadio.Group
          name="assignType"
          label="发布范围"
          options={[
            {
              label: '通讯录（多选）',
              value: '4',
            },
            {
              label: '联络人（多选）',
              value: '5',
            },
          ]}
          rules={[{ required: true, message: '请选择报送范围' }]}

        // tooltip="默认为全部，即所有机构，包括中央媒体"
        />
      </ProFormGroup>

      {/* 联络人（多选） */}
      <AssignAccount
        formRef={formRef}
        visibleAssign={visibleAssignAccount}
        assignsAccounts={dataAssignsAccounts}
        onSave={setVisibleReauestState}
        setVisibleReadReauest={setVisibleReadReauestState}
        setaccountsLenght={setAccountsLenghtState}
      />
      {/* 联络人（多选） */}
      <AssignContact
        formRef={formRef}
        visibleAssign={visibleAssignContact}
        assignsContacts={dataAssignsContactss}
        onSave={setVisibleReauestState}
        setVisibleReadReauest={setVisibleReadReauestState}
        setaccountsLenght={setAccountsLenghtState}
      />

      {/* {vaisibleRequest && (
        <Row>
          <Col span={14}>
            <ProFormSlider
              name="countRead"
              // label="阅读人数"
              width="xs"
              label={
                <>
                  <span
                    style={{
                      color: '#ff4d4f',
                      fontSize: 14,
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  阅读人数
                </>
              }
              hidden={!vaisibleReadRequest}
              max={
                formRef.current?.getFieldValue('assignType') === '4'
                  ? accountsLenght
                  : formRef.current?.getFieldValue('assignContacts')?.length
              }
            />
          </Col>
          <Col span={14}>
            <ProFormSlider
              name="countReceipt"
              width="xl"
              label={
                <>
                  <span
                    style={{
                      color: '#ff4d4f',
                      fontSize: 14,
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  回执人数
                </>
              }
              hidden={!vaisibleReceiptRequest}
              max={
                formRef.current?.getFieldValue('assignType') === '4'
                  ? accountsLenght
                  : formRef.current?.getFieldValue('assignContacts')?.length
              }
            />
          </Col>
        </Row>
      )} */}

      <Divider />
      {/* <Form.Item
        name="content"
        label="选题内容（为保证小程序使用，建议把附件内容复制到编辑器中）"
        rules={[{ required: true, message: '请输入选题内容内容' }]}
      >
        <GdrmTinyMce
          action={`${getApi()}/bulletin/file/upload`}
          onInit={initTinyMce}
          accountId={currentUser?.id}
          organizationName={currentUser?.organizationName}
          defaultContent={content}
        />
      </Form.Item> */}

      <ProCard ghost>
        <ProCard colSpan={'1'} ghost>
          <ProForm.Item
            name="content"
            label={
              <>
                <span
                  style={{
                    color: '#ff4d4f',
                    fontSize: 14,
                    paddingRight: 4,
                  }}
                >
                  *
                </span>
                指令内容
              </>
            }
          >
            <TextEditor
              onInit={(editor) => { }}
              readonly={false}
              onClick={(value) => { }}
              defaultContent=""
              tinyID="tinyId"
            // extra={
            //   <Button
            //     icon={<CoffeeOutlined />}
            //     key="btn_green_submit_preview"
            //     style={{
            //       background: '#87d068',
            //     }}
            //     type="primary"
            //     size="small"
            //     onClick={() => {
            //       setGreen(true);
            //     }}
            //   >
            //     审核
            //   </Button>
            // }
            />
          </ProForm.Item>
        </ProCard>
      </ProCard>
      <FormItem
        name="attachments"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            附件
          </span>
        }
        hidden={!access.宣传指令x发布指令x附件}
      >
        <UploadDragger
          style={{
            marginLeft: '28px',
          }}
          onPreview={(file) => { }}
          access={{
            isPicture: access.宣传指令x发布指令x附件x图片,
            isVideo: access.宣传指令x发布指令x附件x视频,
            isOffice: access.宣传指令x发布指令x附件x办公,
            isOther: access.宣传指令x发布指令x附件x其他,
          }}
          url="/instruct/attachment/save"
        />
      </FormItem>
    </DrawerForm>
  );
};

export default AddRecord;
